//TODO 传入n个中间键，执行当前中间键, 通过对dispatch方法进行增强
export default function applyMiddlewars(...middlewares) {
      // 返回一个增强了dispatch后的函数
      return (createStore) => {
            return (reducer) => {
                  // 获取store值，增强dispatch
                  let store = createStore(reducer);
                  let dispatch = store.dispatch;

                  const midApi = {
                        getState: store.getState,
                        dispatch: (actions, ...args) =>
                              dispatch(actions, ...args),
                  };

                  let chianMiddlewares = middlewares.map((middleware) =>
                        middleware(midApi)
                  );

                  dispatch = compose(chianMiddlewares)(store.dispatch);

                  return {
                        ...store,
                        dispatch,
                  };
            };
      };
}

function compose(chianMiddlewares) {
      if (chianMiddlewares && chianMiddlewares.length === 0) {
            return;
      }

      if (chianMiddlewares.length === 1) {
            return chianMiddlewares[0];
      }

      return chianMiddlewares.reduce((previousValue, currentValue) => {
            return (...args) => previousValue(currentValue(...args));
      });
}
